package com.ssyc.gsk_tk.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ssyc.common.base.LazyBaseFragment;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyListView;
import com.ssyc.common.view.flowlayout.FlowLayout;
import com.ssyc.common.view.flowlayout.TagAdapter;
import com.ssyc.common.view.flowlayout.TagFlowLayout;
import com.ssyc.gsk_tk.R;
import com.ssyc.gsk_tk.adapter.LvSelfAnswerAdapter;
import com.ssyc.gsk_tk.bean.ArticleInfo;
import com.ssyc.gsk_tk.bean.OverQuestion;
import com.ssyc.gsk_tk.bean.QuestionInfo;
import com.ssyc.gsk_tk.bean.TkInputInfo;
import com.ssyc.gsk_tk.util.TkKeys;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 选词填文章
 * Created by Administrator on 2018/9/3 0003.
 */

public class TkChooseWordInArticleFragment extends LazyBaseFragment {

    //展示提供选择单词的流式布局
    private TagFlowLayout flowLayout;
    //流式布局适配器
    private TagAdapter adapter;

    /*完成状态下需要显示的相关布局*/
    //展示以完成状态下的线性整体布局
    private LinearLayout llShowAnswer;
    //文章内容
    private TextView tvArticle;
    //展示自己答案的列表
    private MyListView lvOwnAnswer;
    //展示正确答案的列表
    private MyListView lvRightAnswer;
    //解析
    private TextView tvParseAnswer;
    //正确率的列表
    private MyListView lvParseAnswer;

    //解析的列表
    private MyListView lv_expain_answer;


    //未完成传递的页面对象
    private QuestionInfo.ListBean.ItemBean info;

    //已完成的页面对象
    private OverQuestion.ListBean.ItemBean overinfo;

    //传递的页面的json数据
    private String jsonData;

    //页面数据对象
    private ArticleInfo articleInfo;

    //切割字符串的下划线
    private static final String regx = "__";

    //切割的正则表达式,以2个下划线开头并且以2个下划线结尾,中间可以是任意字母和数字不限制个数
    private String reg = "_{2,}[0-9a-zA-Z]+_{2,}";
    //使用正则表达式切割后的字符串集合
    private String[] sentences;
    //用于保存用户输入的内容,初始值为服务器返回的__i__
    private Map<Integer, String> inputContent;
    //正确答案的集合
    private List<ArticleInfo.ListABean> listA;

    //已完成状态下的解析的
    private String[] analysis;
    private String[] ownAnsers;

    //所有小题选项的正确率
    private List<OverQuestion.ListBean.ItemBean.ProbabilityBean> probability;

    /**
     * 构造方法
     *
     * @param item
     * @return
     */
    public static final TkChooseWordInArticleFragment newInstance(QuestionInfo.ListBean.ItemBean item, OverQuestion.ListBean.ItemBean overData) {
        TkChooseWordInArticleFragment teacherGoldFragment = new TkChooseWordInArticleFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", item);
        bundle.putSerializable("overdata", overData);
        teacherGoldFragment.setArguments(bundle);
        return teacherGoldFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tk_choose_word_in_article;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {
    }

    @Override
    protected void init(View view, Bundle savedInstanceState) {
        super.init(view, savedInstanceState);
        //显示内容
        showContent();

        //初始化视图
        initView(view);

        //获取数据
        initIntent();

        //设置顶部流式布局展示单词的数据
        initFlowLayoutData();

        //同步底部文章数据的方法
        intiStateBottom();
    }

    /**
     * 采用正则表达式切割服务器返回的答案
     */
    private void intiStateBottom() {
        if (articleInfo != null && !TextUtils.isEmpty(articleInfo.getContent())) {
            //服务器返回的文章的内容
            String articleContent = articleInfo.getContent();

            //采用切割的方式来实现,采用正则表达式__任意数字和字母__ 正则表达式来切割来切割
            sentences = articleContent.split(reg);

            //获取服务器返回的填空个数
            List<ArticleInfo.ListABean> listA = articleInfo.getListA();

            inputContent = new HashMap<>();

            if (info != null) {
                //初始化创建Map用以保存输入的内容,默认值是__i__
                for (int i = 0; i < listA.size(); i++) {
                    inputContent.put(i, "__" + (i + 1) + "__");
                }
            } else if (overinfo != null) {
                for (int i = 0; i < ownAnsers.length; i++) {
                    inputContent.put(i, "__" + ownAnsers[i] + "__");
                }
            }
            sysTvArticleContentState();
        }
    }

    /**
     * 同步点击事件的方法
     */
    private void sysTvArticleContentState() {

        String content = "";

        //拼接需要显示的字符串
        //以__结尾,切割的数组长度和填空的位置一样
        //不以__结尾的话,切割的字符串数组长度比需要填空的位置多一个
        if (sentences.length == inputContent.size()) {
            //以__结尾,切割的数组长度和填空的位置一样
            for (int i = 0; i < sentences.length; i++) {
                if (!TextUtils.isEmpty(inputContent.get(i))) {
                    content += sentences[i] + inputContent.get(i);
                }
            }
        } else {
            //不以__结尾的话,切割的字符串数组长度比需要填空的位置多一个
            for (int i = 0; i <= sentences.length - 2; i++) {
                //sentences的是8,但是inputContent的长度是7
                content += sentences[i] + inputContent.get(i);
            }
            content += sentences[sentences.length - 1];
        }

        //计算需要变色的位置
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(content);
        for (int i = 0; i < inputContent.size(); i++) {
            //定义变量记录点击的位置
            int index = i;
            //第一个变色位置的开始坐标sentences[0].length()
            //第一个变色结束的位置 sentences[0].length() + inputContent.get(0).length
            //第二个变色位置的开始坐标sentences[0].length()+inputContent.get(0).length()+sentences[1].length()
            //第二个变色的结束位置 start+inputContent.get(1).length
            //第三个变色位置的开始坐标sentences[0].length()+inputContent.get(0).length()+sentences[1].length()+inputContent.get(1).length()
            int start = 0;
            int end = 0;
            if (i == 0) {
                start = sentences[0].length();
                end = start + inputContent.get(0).length();
            } else {
                for (int j = 0; j <= i; j++) {
                    start += sentences[j].length();
                }
                for (int k = 0; k <= i - 1; k++) {
                    start += inputContent.get(k).length();
                }

                end = start + inputContent.get(i).length();
            }

            stringBuilder.setSpan(new TextClick() {
                @Override
                public void onClick(View view) {
                    Log.i("test", "被点击的位置是:" + index);
                    if (info != null) {
                        //只有在未完成状态下才需要点击弹框的操作
                        showInputPop(index);
                    }
                }
            }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        tvArticle.setText(stringBuilder);

        //设置该方法后,点击事件才能生效
        tvArticle.setMovementMethod(LinkMovementMethod.getInstance());

    }


    /**
     * 初始化视图
     *
     * @param view
     */
    public void initView(View view) {
        flowLayout = view.findViewById(R.id.flowlayout);
        tvArticle = view.findViewById(R.id.tv_article);
        lvOwnAnswer = view.findViewById(R.id.lv_own_answer);
        lvRightAnswer = view.findViewById(R.id.lv_right_answer);
        tvParseAnswer = view.findViewById(R.id.tv_parse_answer);
        llShowAnswer = view.findViewById(R.id.ll_show_answer);
        lvParseAnswer = view.findViewById(R.id.lv_parse_answer);
        lv_expain_answer = view.findViewById(R.id.lv_expain_answer);
    }


    /**
     * 获取页面数据
     */
    private void initIntent() {
        info = (QuestionInfo.ListBean.ItemBean) getArguments().getSerializable("data");

        //已完成的数据对象
        overinfo = (OverQuestion.ListBean.ItemBean) getArguments().getSerializable("overdata");


        if (info != null) {
            //未完成
            //获取页面的JSON数据
            jsonData = info.getContent();
            if (!TextUtils.isEmpty(jsonData)) {
                articleInfo = GsonUtil.jsonToBean(jsonData, ArticleInfo.class);
                listA = articleInfo.getListA();
            }

            //答案展示部分不需要展示
            llShowAnswer.setVisibility(View.GONE);

            //展示问题的TextView不需要点击事件
            tvArticle.setEnabled(true);

        } else if (overinfo != null) {
            //已完成
            //获取题目的解析
            analysis = overinfo.getAnalysis().split("￠");

            //你的作答
            ownAnsers = overinfo.getOption_content().split("￠");

            //如果是已完成则解析overinfo
            jsonData = overinfo.getContent();

            //获取所有小题的正确率
            probability = overinfo.getProbability();

            if (!TextUtils.isEmpty(jsonData)) {
                articleInfo = GsonUtil.jsonToBean(jsonData, ArticleInfo.class);
                listA = articleInfo.getListA();
            }

            //答案展示部分需要展示
            llShowAnswer.setVisibility(View.VISIBLE);

            //展示问题的TextView不需要点击事件
            tvArticle.setEnabled(false);

            //设置你的作答的列表数据
            initOwnAnswerLv();

            //设置正确答案的列表数据
            initRightAnswerLv();

            //设置答案正确率的列表数据
            initRightAnswerPresentLv();

            //设置解析的列表展示
            initParseAnswerLv();
        }

    }

    /**
     * 设置你的作答的列表数据
     */
    private void initOwnAnswerLv() {
        //创建你的作答的数据
        List<TkInputInfo> selfDatas = new ArrayList<>();
        for (int i = 0; i < ownAnsers.length; i++) {
            TkInputInfo info = new TkInputInfo();
            info.index = "(" + (i + 1) + ")";
            info.content = ownAnsers[i];
            selfDatas.add(info);
        }
        LvSelfAnswerAdapter lvSelfAdapter = new LvSelfAnswerAdapter(getContext(), selfDatas, R.layout.tk_lv_answer);
        lvOwnAnswer.setAdapter(lvSelfAdapter);
    }


    /**
     * 设置正确答案的列表数据
     */
    private void initRightAnswerLv() {
        //创建正确答案的数据
        List<TkInputInfo> rightDatas = new ArrayList<>();
        for (int i = 0; i < listA.size(); i++) {
            TkInputInfo info = new TkInputInfo();
            info.index = "(" + (i + 1) + ")";
            info.content = listA.get(i).getTxtA();
            rightDatas.add(info);
        }
        LvSelfAnswerAdapter lvRightAdapter = new LvSelfAnswerAdapter(getContext(), rightDatas, R.layout.tk_lv_answer);
        lvRightAnswer.setAdapter(lvRightAdapter);
    }


    /**
     * 设置正确率的列表数据
     */
    private void initRightAnswerPresentLv() {
        //创建解析的数据集合
        List<TkInputInfo> parseAnswerDatas = new ArrayList<>();
        for (int i = 0; i < listA.size(); i++) {
            TkInputInfo info = new TkInputInfo();
            info.index = "(" + (i + 1) + ")";

            //这里Content理解为该题的正确率
            if (probability != null && probability.size() != 0) {

                if(TextUtils.isEmpty(probability.get(i).getpro())){
                    info.content = "100.0%";
                }else{
                    info.content = probability.get(i).getpro();
                }
            } else {
                info.content = "100.0%";
            }
            parseAnswerDatas.add(info);
        }
        LvSelfAnswerAdapter lvParseAnswerAdapter = new LvSelfAnswerAdapter(getContext(), parseAnswerDatas, R.layout.tk_lv_parse_answer);
        lvParseAnswer.setAdapter(lvParseAnswerAdapter);
    }


    /**
     * 设置解析的列表数据
     */
    private void initParseAnswerLv() {
        List<String> contents = new ArrayList<>();
        //获取整个题目的解析,将解析的第一个元素使用1分割
        if (!analysis[0].startsWith("1")) {
            //表示有题目解析
            String[] parseAnswers = analysis[0].split("1");

            //获取整体的解析,第一个元素就是整个题目的翻译解析
            String questionParse = parseAnswers[0];
            //将整个问题的解析放入集合
            contents.add(questionParse);
            contents.add("1" + parseAnswers[1]);
            //将其它的解析添加到集合中
            for (int i = 1; i < analysis.length; i++) {
                contents.add(analysis[i]);
            }

        } else {
            //表示没有题目解析
            for (int i = 0; i < analysis.length; i++) {
                contents.add(analysis[i]);
            }
        }

        List<TkInputInfo> parseAnswerDatas = new ArrayList<>();
        for (int i = 0; i < contents.size(); i++) {
            TkInputInfo info = new TkInputInfo();
            info.content = contents.get(i);
            parseAnswerDatas.add(info);
        }
        LvSelfAnswerAdapter lvParseAnswerAdapter = new LvSelfAnswerAdapter(getContext(), parseAnswerDatas, R.layout.tk_lv_parse_right_answer);
        lv_expain_answer.setAdapter(lvParseAnswerAdapter);
    }


    /**
     * 设置流式布局的数据
     */
    private void initFlowLayoutData() {
        if (articleInfo == null) {
            Log.i("test", "没有需要展示的单词数据");
            return;
        }

        //获取需要展示的单词
        List<ArticleInfo.ListRBean> words = articleInfo.getListR();
        if (words == null || words.size() == 0) {
            Log.i("test", "没有需要展示的单词数据");
            return;
        } else {
            List<String> showWords = new ArrayList<>();
            for (int i = 0; i < words.size(); i++) {
                showWords.add(words.get(i).getTxtR());
            }
            final LayoutInflater mInflater = LayoutInflater.from(getActivity());
            //设置流式布局的数据
            flowLayout.setAdapter(new TagAdapter<String>(showWords) {
                @Override
                public View getView(FlowLayout parent, int position, String s) {
                    TextView tv = (TextView) mInflater.inflate(R.layout.tk_tv_article,
                            flowLayout, false);
                    tv.setText(s);
                    return tv;
                }
            });
        }
    }

    /**
     * 点击空格位置弹出输入框的方法
     *
     * @param index
     */
    private void showInputPop(int index) {
        PopUpManager.showPop(getContext(), R.layout.tk_pop_input_form_blank, 0.3f, getActivity(), new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                //取消
                TextView tvCancel = view.findViewById(R.id.tv_cancel);
                //保存
                TextView tvOk = view.findViewById(R.id.tv_ok);

                //提示
                TextView tvMsg = view.findViewById(R.id.tv_pop_content);
                tvMsg.setText("请输入第"+(index+1)+"空答案");

                //输入框
                EditText etInput = view.findViewById(R.id.et_input);

                tvCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //关闭弹框
                        PopUpManager.dismiss();
                    }
                });

                tvOk.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //点击确定后的操作
                        //第一步:获取输入框的文字,进行非空判断
                        String content = etInput.getText().toString().trim();
                        if (TextUtils.isEmpty(content)) {
                            //没有输入单词
                            UiUtils.Toast("您还没有输入单词", false);
                            return;
                        } else {
                            //已经输入了单词
                            //第二步:将输入的单词回显到点击的空格位置

                            //将用于保存输入框的内容的集合中点击的位置的值进行同步
                            inputContent.put(index, regx + content + regx);

                            //再次设置点击事件
                            sysTvArticleContentState();
                            PopUpManager.dismiss();


                            //通过EventBs将用户作答本小题的相关信息传递给TkMainActivity保存
                            //currPos对应的每个大题的小题的位置
                            int choosePos = index;
                            //用户选的输入的单词
                            String chooseAnswer = content;
                            //是否如正确
                            boolean chooseResult = false;
                            if (content.equals(listA.get(index).getTxtA())) {
                                //用户作答正确
                                chooseResult = true;
                            } else {
                                //用户作答错误
                                chooseResult = false;
                            }
                            //回传当前提醒的TypeId,阅读题型对应的是14
                            int typeId = 14;
                            BusInfo busInfo = new BusInfo();
                            busInfo.tkMsg = TkKeys.TKMsg;
                            busInfo.tkChoosePos = choosePos;
                            busInfo.tkChooseAnswer = chooseAnswer;
                            busInfo.tkChooseResult = chooseResult;
                            busInfo.typeId = typeId;
                            EventBus.getDefault().post(busInfo);
                        }
                    }
                });
            }
        });
    }


    /**
     * 点击事件
     */
    private abstract class TextClick extends ClickableSpan {
        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setUnderlineText(false);
            ds.setColor(Color.parseColor("#EC8628"));
        }
    }
}
